package sseemitter

import (
	"fmt"
	"net/http"
)

var Emitter = NewSSEmitter()

// HandleSSEEmitter 处理 SSEEmitter请求
func HandleSSEEmitter(resp http.ResponseWriter, req *http.Request) {
	resp.Header().Set("Content-Type", "text/event-stream")
	resp.Header().Set("Cache-Control", "no-cache")
	resp.Header().Set("Connection", "keep-alive")

	client := make(chan string)
	Emitter.AddClient(client)
	defer Emitter.RemoveClient(client)

	//循环获取消息
	for {
		//阻塞，直到有信息来位置
		event := <-client
		//将内容写道返回resp对象中
		fmt.Fprint(resp, event)
		//刷新，这里因为我们前面设置了响应头所以这里是文本事件流
		resp.(http.Flusher).Flush()
	}
}
